document.getElementById('loginForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const messageEl = document.getElementById('message');

    // 简单前端验证
    if (!username || !password) {
        showMessage('用户名和密码不能为空', 'error');
        return;
    }

    // 发送登录请求
    fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password })
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('登录失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                showMessage('登录成功，正在跳转...', 'success');
                // 登录成功后的跳转
                setTimeout(() => {
                    window.location.href = '/dashboard';
                }, 1500);
            } else {
                showMessage(data.message || '登录失败', 'error');
            }
        })
        .catch(error => {
            showMessage(error.message || '登录失败', 'error');
        });
});

function showMessage(message, type) {
    const messageEl = document.getElementById('message');
    messageEl.textContent = message;
    messageEl.className = 'message ' + type;
}